import Router from 'next/router'
import axios from 'axios'
import {message } from 'antd'
import {signOut } from '../lib/auth'
import cookie from "js-cookie"
import config from '../config'

axios.defaults.timeout = 300000
// axios.defaults.withCredentials= true // default

axios.defaults.baseURL = config.remoteHost;
// http request 拦截器
axios.interceptors.request.use(
    config => {
        let token = '';
        if (process.browser) {
            token = cookie.get('token');
        }else{
            if(config.params&&config.params.token){
                token = config.params.token
                delete config.params.token
            }else if(config.body&&config.body.token){
                token = config.body.token
                delete config.body.token
            }
        }
        if (token) {
            config.headers['x-access-token'] = `${token}`
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)
axios.interceptors.response.use(
    response => {
        if (response.data.code === 0) { 
            message.error(response.data.message)
        } 
        return response
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 404:
                    
                    break;
                case 401:
                    // 401 清除token信息并跳转到登录页面
                    message.error('请重新登录');
                    signOut()
                    Router.push('/login')
                    break;
                case 403:
                    message.error('抱歉，您没有权限访问,请与系统管理员联系!')
                    break;
                default:
                    message.error('请求失败，服务器错误!')
                    break;
            }
        }
        return Promise.reject(error)
    }
)

function uploadHttp (method='post',url,formData, callback){
    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }
    return axios({
        method: method,
        url: url,
        data: formData,
        config,
        onUploadProgress: function(progressEvent) {
            if (progressEvent.lengthComputable) {
                if (callback && typeof callback === 'function') {
                    callback(progressEvent)
                }
            }
        }
    });
}




//登录
export const login = (username, password) => { return axios.post('/api/login', { username: username, password: password }) }
//注册
export const regist = (username, email, password) => { return axios.post('/api/regist', { username, email, password }) }
//获取登录用户信息
export const getUserInfo = (params) => { return axios.get('/api/userInfo',{ params }) }
//修改用户信息
export const updateUserInfo = (data) => { return axios.put('/api/updateUserInfo',data) }
//更新我的头像
export const updateAvatar = (data, callback) => { return uploadHttp('put', '/api/updateAvatar', data, callback) }

//获取类型和标签
export const getCateAndTag = () => { return axios.get('/api/categoriesAndTags') }
//发表文章
export const createArticle = (data) => { return axios.post('/api/articles/save', data) }
//创建草稿
export const createDraft = (data) => { return axios.post('/api/draft/save',data) }
//获取草稿
export const getDrafts = () => { return axios.get('/api/drafts') }
//删除文章
export const removeArticle = (ids) => { return axios.delete('/api/articles/' + ids) }
//获取文章列表
export const getArticleList = (params) => { return axios.get('/api/articles', { params }) }

//获取用户文章列表
export const getArticleListByUser = (params) => { return axios.get(`/api/users/${params.userId}/articles`, { params }) }


//获取文章详情
export const getArticleDetail = ({id,token}) => { return axios.get('/api/articles/' + id + '/front',{ params:{token} }) }
//根据ID获取文章
export const getArticleById = ({id,token}) => { return axios.get('/api/articles/' + id ,{ params:{token} }) }


//文章点赞
export const toggleLike = (id) => { return axios.put('/api/articles/' + id + '/like') }
//文章收藏
export const toggleCollect = (id) => { return axios.put('/api/articles/' + id + '/collect') }
//发表评论
export const submitComment = (article_id, data) => { return axios.post('/api/articles/' + article_id + '/comments', data) }
//获取评论
export const getComments = (article_id, params) => { return axios.get('/api/articles/' + article_id + '/comments', { params: params }) }
//获取文章评论用户
export const getCommentUsers = (article_id, params) => { return axios.get('/api/articles/' + article_id + '/comments/users', { params: params }) }
//评论点赞
export const addCommentLike = (cId) => { return axios.put('/api/comments/' + cId + '/like') }
//删除我的评论
export const removeComment = (id) => { return axios.delete('/api/comments/'+id) }
//用户关注
export const toggleFollow = (uid) => { return axios.put('/api/users/' + uid + '/follow') }



//获取用户信息
export const batchGetUsersInfo = (params) => { return axios.get('/api/users/info/batch',{ params }) }






//获取我的文章
export const getArticlesByUserId = (id, params) => { return axios.get('/api/users/' + id + '/articles', { params }) }

//获取我的关注
export const getFollowsByUserId = (id, params) => { return axios.get('/api/users/' + id + '/follows', { params }) }

//获取我的粉丝
export const getFansByUserId = (id, params) => { return axios.get('/api/users/' + id + '/fans', { params }) }

//获取我的信息
export const getInfoByUserId = (id) => { return axios.get('/api/users/' + id + '/info') }


//更新我的个人设置
export const updateSetting = (data) => { return axios.put('/api/me/settings',data) }




//上传文件
export const uploadImage = (formData, callback) => {
    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }
    return axios({
        method: 'post',
        url: '/api/uploadImage?_csrf=Ryzwmaq4eh-uOfB4jkYnu-_R',
        data: formData,
        config,
        onUploadProgress: function(progressEvent) {
            if (progressEvent.lengthComputable) {
                if (callback && typeof callback === 'function') {
                    callback(progressEvent)
                }
            }
        }
    });
}